//
//  TWSubscriptionViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/9.
//  Copyright © 2017年 个人. All rights reserved.
//  关注页面

import UIKit
import SVProgressHUD

let FromSubscriptionVc = "TWSubscriptionViewController"

class TWSubscriptionViewController: UITableViewController {

    fileprivate lazy var subscriptionDateArray : NSMutableArray = NSMutableArray()
    fileprivate lazy var nextPageUrl : String = String()
    fileprivate lazy var footerView : TWFooterView = TWFooterView.createFooterView()        // 脚部视图
    fileprivate lazy var footerNullView : UILabel = UILabel()                               // 空的脚部视图
    fileprivate lazy var headerView : TWFooterView = TWFooterView.createFooterView()        // 下拉刷新
    fileprivate lazy var authorVc : TWAuthorViewController = TWAuthorViewController()
    fileprivate lazy var searchViewAnimator : TWSearchAnimator = TWSearchAnimator()
//    fileprivate lazy var briefViewController : TWBriefViewController = TWBriefViewController()
    
    var isHeaderRefreshing : Bool = false
    var isFooterRefreshing : Bool = false
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupTableView()
        setupNavigationBar()
        setupNotifications()
        setupRefreshView()
        setupNullFooterView()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- UI界面
extension TWSubscriptionViewController {
    // 导航栏
    fileprivate func setupNavigationBar(){
        let leftButton = UIButton(type: .custom)
        leftButton.setTitle("全部作者", for: .normal)
        leftButton.setTitleColor(UIColor.black, for: .normal)
        leftButton.titleLabel?.font = UIFont(name: "FZLTXIHJW--GB1-0", size: 14)
        leftButton.addTarget(self, action: #selector(leftBarButtonItemDidClick), for: .touchUpInside)
        leftButton.sizeToFit()
        // 往导航栏左边添加一个间隙
        let leftItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        leftItem.width = -10
        navigationItem.leftBarButtonItems = [leftItem,UIBarButtonItem(customView: leftButton)]
        
        // 中间
        let titleLabel = UILabel()
        titleLabel.text = "Subscription"
        titleLabel.font = UIFont(name: "Lobster 1.4", size: 28)
        titleLabel.textColor = UIColor.black
        titleLabel.sizeToFit()
        navigationItem.titleView = titleLabel
        
        let rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "bar_ic_search_44x44_"), for: .normal)
        rightButton.addTarget(self, action: #selector(rightBarButtonItemDidClick), for: .touchUpInside)
        rightButton.sizeToFit()
        // 往导航栏右边添加一个间隙
        let rightItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        rightItem.width = -15
        navigationItem.rightBarButtonItems = [rightItem,UIBarButtonItem(customView: rightButton)]
    }
    // tableView
    fileprivate func setupTableView() {
        automaticallyAdjustsScrollViewInsets = false
        tableView.backgroundColor = UIColor.white
        tableView.frame = view.bounds
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: NavigationBarHeight, left: 0, bottom: TabBarHeight, right: 0)
        // 注册
        tableView.register(UINib(nibName: "TWVideoCollectionWithBrief", bundle: nil), forCellReuseIdentifier: VideoCollectionWithBrief)
        tableView.register(UINib(nibName: "TWVideoCollectionOfHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfHorizontalScrollCard)
    }
    fileprivate func setupNullFooterView(){
        // 没有数据时的tableFooterView
        footerNullView = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        footerNullView.text = "-end-"
        footerNullView.font = UIFont.init(name: "Lobster1.4", size: 15)
        footerNullView.textAlignment = .center
    }
    fileprivate func setupRefreshView(){
        headerView.frame = CGRect(x: 0, y: -DiscovertitleViewHeight, width: UIScreen.main.bounds.width, height: DiscovertitleViewHeight)
        headerView.backgroundColor = UIColor.clear
        tableView.addSubview(headerView)
        headerBeginRefreshing()
    }
}

// MARK:- 通知
extension TWSubscriptionViewController {
    fileprivate func setupNotifications(){
        NotificationCenter.default.addObserver(self, selector: #selector(subscriptionViewControllerTabBarButtonDidRepeatClick), name: NSNotification.Name(rawValue: TabBarButtonDidRepeatClickNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(detailCollectionViewCellDidClick(note:)), name: NSNotification.Name(rawValue: DetailCollectionViewCellDidClickNotification), object: nil)
    }
}

// MARK:- 监听点击
extension TWSubscriptionViewController {
    @objc fileprivate func leftBarButtonItemDidClick(){
        present(authorVc, animated: true, completion: nil)
    }
    @objc fileprivate func rightBarButtonItemDidClick(){
        let searchVc : TWSearchViewController = TWSearchViewController()
        searchVc.modalPresentationStyle = .custom
        searchVc.transitioningDelegate = searchViewAnimator
        present(searchVc, animated: true, completion: nil)
    }
    @objc fileprivate func subscriptionViewControllerTabBarButtonDidRepeatClick(){
        tableView.setContentOffset(CGPoint(x: 0, y: -NavigationBarHeight), animated: true)
    }
    @objc fileprivate func detailCollectionViewCellDidClick(note : NSNotification){
        let dict = note.object as! [String : AnyObject]
        if dict.keys.first == FromSubscriptionVc {
            let selectModel = dict.values.first as! TWItemModel // 拿到当前选中的模型
            let animationViewController : TWAnimationViewController = TWAnimationViewController()
            animationViewController.itemModel = selectModel
            present(animationViewController, animated: true, completion: nil)
        }
    }
}

// MARK:- 请求数据
extension TWSubscriptionViewController {
    
    /// 请求最新网络数据
    fileprivate func loadNewData(urlString : String){
        loadingSubscriptionData(isLoadNewData: true, isLoadMoreData: false, urlString: urlString)
    }
    /// 加载更多数据
    fileprivate func loadMoreData(){
        loadingSubscriptionData(isLoadNewData: false,isLoadMoreData: true,  urlString: nextPageUrl)
    }
    
    private func loadingSubscriptionData(isLoadNewData : Bool, isLoadMoreData: Bool, urlString : String){
        TWNetworkTool.shareInstance.loadSubscriptionData(urlString: urlString) { (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败！")
                if isLoadNewData {
                    self.headerEndRefreshing()
                } else if isLoadMoreData {
                    self.footerEndRefresh()
                }
                return
            }
            guard let result = result else {
                return
            }
            let next = result["nextPageUrl"]
            if String(describing: next!) == "<null>" {
                self.footerEndRefresh()
                self.tableView.tableFooterView = self.footerNullView
                return
            } else {
                self.nextPageUrl = next as! String
            }
            // 处理cell相关的数据
            self.dealWithData(isLoadNewData : isLoadNewData, result: result)
        }
    }
    private func dealWithData(isLoadNewData : Bool, result : [String : AnyObject]){
        // 需要展示主体数据的数组
        let itemListArray = result["itemList"] as! [[String : AnyObject]]
        let tempArray : NSMutableArray = NSMutableArray()
        
        // 遍历数组,判断是什么类型
        for item in itemListArray {
            let dataType = item["type"] as! String
            if dataType == VideoCollectionWithBrief {
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionWithBrief : itemModel])
            } else if dataType == VideoCollectionOfHorizontalScrollCard {
                let itemModel : TWVideoCollectionOfHorizontalScrollCardModel = TWVideoCollectionOfHorizontalScrollCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionOfHorizontalScrollCard : itemModel])
            } else {
                TWLog(message: "这是一组未知类型的数据")
            }
        }
        
        if isLoadNewData {
            subscriptionDateArray.removeAllObjects()
            for item in tempArray {
                subscriptionDateArray.add(item)
            }
        } else {
            for item in tempArray {
                subscriptionDateArray.add(item)
            }
        }
        
        // 刷新UI
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.tableView.reloadData()
            self.tableView.tableFooterView = self.footerView
            if isLoadNewData {
                self.headerEndRefreshing()
            } else {
                self.footerEndRefresh()
            }
            SVProgressHUD.dismiss()
        }
    }
}

// MARK:- tableView的代理方法
extension TWSubscriptionViewController {
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 取出当前对应的类型
        let data = subscriptionDateArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型计算高度
        if key == VideoCollectionWithBrief {
            return videoCollectionWithBriefCellHeight
        } else if key == VideoCollectionOfHorizontalScrollCard {
            return videoCollectionOfHorizontalScrollCardCellHeight
        } else {
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.tableFooterView?.isHidden = subscriptionDateArray.count == 0 ? true : false
        return subscriptionDateArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 取出当前对应的类型
        let data = subscriptionDateArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        if key == VideoCollectionWithBrief {
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionWithBrief, for: indexPath) as! TWVideoCollectionWithBrief
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.model = itemCollectionModel
            cell.bottomCollectionView.fromWhichVc = FromSubscriptionVc
            cell.videoCollectionWithBriefDelegate = self
            return cell
        } else if key == VideoCollectionOfHorizontalScrollCard {
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfHorizontalScrollCard, for: indexPath) as! TWVideoCollectionOfHorizontalScrollCardCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfHorizontalScrollCardModel
            cell.model = itemCollectionModel
            cell.horizontalScrollCardCellDelegate = self
            cell.bottomCollectionView.fromWhichVc = FromSubscriptionVc
            return cell
        } else {
            return UITableViewCell()
        }
    }
}

// MARK:- VideoCollectionWithBriefDelegate的代理方法
extension TWSubscriptionViewController : VideoCollectionWithBriefDelegate {
    func pushViewControllerWith(model: TWVideoCollectionOfAuthorWithCoverModel) {
        let briefViewController : TWBriefViewController = TWBriefViewController()
        briefViewController.model = model
        self.navigationController?.pushViewController(briefViewController, animated: true)
    }
}

// MARK:- VideoCollectionOfHorizontalScrollCardCellDelegate的代理方法
extension TWSubscriptionViewController : VideoCollectionOfHorizontalScrollCardCellDelegate {
    func horizontalScrollCardCellTitleDidClick(model: TWVideoCollectionOfHorizontalScrollCardModel) {
        let themeVC : TWTheme_ViewController = TWTheme_ViewController()
        themeVC.model = model
        self.navigationController?.pushViewController(themeVC, animated: true)
    }
}

// MARK:- scrollView的代理方法
extension TWSubscriptionViewController {
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let insetTop = NavigationBarHeight
        // 滚动偏移量
        let offset = -(tableView.contentOffset.y + insetTop)  // 默认为0
        dealFooter(offset: offset)
    }
    
    // 用户松开scrollView时调用
    override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        let insetTop = NavigationBarHeight
        // 滚动偏移量
        let offset = -(tableView.contentOffset.y + insetTop)
        if offset >= refreshingOffset {
            headerBeginRefreshing()
        }
    }
}

// MARK:- 刷新相关的方法
extension TWSubscriptionViewController {
    
    fileprivate func dealFooter(offset : CGFloat){
        // 还没有任何内容的时候，不需要判断
        if tableView.contentSize.height == 0 {
            return
        }
        if isFooterRefreshing {
            return
        }
        // 计算偏移量 = 内容的顶部和frame的顶部的差值,tableView.contentSize包括header和footer
        let ofsetY = tableView.contentSize.height + tableView.contentInset.bottom - tableView.frame.height
        if tableView.contentOffset.y >= ofsetY && self.tableView.contentOffset.y > -(self.tableView.contentInset.top) {
            footerBeginRefresh()
        }
    }
    // MARK:- 刷新相关
    func footerBeginRefresh() {
        if isFooterRefreshing {
            return
        }
        // 进入刷新状态
        isFooterRefreshing = true
        footerView.addRotationAnimation()
        loadMoreData()
    }
    func footerEndRefresh() {
        isFooterRefreshing = false
        footerView.loading_in_ImageView.layer.removeAllAnimations()
    }
    
    func headerBeginRefreshing(){
        if isHeaderRefreshing {
            return
        }
        isHeaderRefreshing = true
        headerView.addRotationAnimation()
        UIView.animate(withDuration: 0.25, animations: {
            var inset : UIEdgeInsets = self.tableView.contentInset
            inset.top += 40
            self.tableView.contentInset = inset
            // 修改偏移量
            self.tableView.contentOffset = CGPoint(x: self.tableView.contentOffset.x, y: -inset.top)
        })
        loadNewData(urlString: SubscriptionUrlString)
    }
    
    func headerEndRefreshing(){
        isHeaderRefreshing = false
        UIView.animate(withDuration: 0.25, animations: {
            var inset : UIEdgeInsets = self.tableView.contentInset
            inset.top -= 40
            self.tableView.contentInset = inset
        }) { (_) in
            self.headerView.loading_in_ImageView.layer.removeAllAnimations()
        }
    }
}
